package com.park.web;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;

import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import com.park.web.util.pdf.PdfUtil;

public class TextParser {
	private static TextParser parser = null;

	private TextParser(){}

	public static synchronized TextParser getInstance(){
		if(parser == null){
			parser = new TextParser();
		}
		return parser;
	}

	
	/** 
     * 图片转PDF 
     * @param sourceFile 
     * @param destFile 
     * @return 
     */  
    public static File picToPdf(String sourceFile, String destFile) {  
        File inputFile = new File(sourceFile);  
        if (!inputFile.exists()) {  
            return null;// 找不到源文件, 则返回null  
        }  
        // 如果目标路径不存在, 则新建该路径  
        File outputFile = new File(destFile);  
        if (!outputFile.getParentFile().exists()) {  
            outputFile.getParentFile().mkdirs();  
        }  
        ArrayList<String> imageUrllist = new ArrayList<String>();  
        imageUrllist.add(sourceFile);  
        return imgToPdf(imageUrllist, destFile);  
    }  
      
     /** 
     * iText转各种图片为pdf 
     * @param imageUrllist 
     * @param mOutputPdfFileName 
     * @return 
     */  
    public static File imgToPdf(ArrayList<String> imageUrllist,String mOutputPdfFileName) {   
        if(null == imageUrllist){  
            return null;  
        }  
        long beginTime = System.nanoTime();  
        Document doc = new Document(PageSize.A4, 20, 20, 20, 20);    
        try {    
            PdfWriter.getInstance(doc, new FileOutputStream(mOutputPdfFileName));    
            doc.open();    
            for (int i = 0; i < imageUrllist.size(); i++) {    
                doc.newPage();    
//                doc.add(new Paragraph("简单使用iText"));    
                Image png1 = Image.getInstance(imageUrllist.get(i));    
                float heigth = png1.getHeight();    
                float width = png1.getWidth();    
                int percent = getPercent(heigth, width);    
                png1.setAlignment(Image.MIDDLE);    
                png1.scalePercent(percent+3);// 表示是原来图像的比例;    
                doc.add(png1);    
            }    
            doc.close();    
        } catch (FileNotFoundException e) {    
            e.printStackTrace();    
        } catch (DocumentException e) {    
            e.printStackTrace();    
        } catch (IOException e) {    
            e.printStackTrace();    
        }    
    
        File mOutputPdfFile = new File(mOutputPdfFileName);    
        if (!mOutputPdfFile.exists()) {    
            mOutputPdfFile.deleteOnExit();    
            return null;    
        }   
          
        try {    
            mOutputPdfFile.createNewFile();    
        } catch (IOException e) {    
            e.printStackTrace();    
        }    
        long endTime = System.nanoTime();  
        System.out.println("图片转pdf耗时: " + (endTime - beginTime) / 1000000000 + " 秒  " + imageUrllist.toString());  
        return mOutputPdfFile;    
    }   
    
    /**  
     * 第二种解决方案，统一按照宽度压缩 这样来的效果是，所有图片的宽度是相等的，自我认为给客户的效果是最好的  
     *  
     * @param args  
     */    
    public static int getPercent2(float h, float w) {    
        int p = 0;    
        float p2 = 0.0f;    
        p2 = 530 / w * 100;    
        p = Math.round(p2);    
        return p;    
    }  
    
    /**  
     * 第一种解决方案 在不改变图片形状的同时，判断，如果h>w，则按h压缩，否则在w>h或w=h的情况下，按宽度压缩  
     *  
     * @param h  
     * @param w  
     * @return  
     */    
    
    public static int getPercent(float h, float w) {    
        int p = 0;    
        float p2 = 0.0f;    
        if (h > w) {    
            p2 = 297 / h * 100;    
        } else {    
            p2 = 210 / w * 100;    
        }    
        p = Math.round(p2);    
        return p;    
    }    
	
	public void text2pdf(String text,String pdf) throws DocumentException, IOException{
//		BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UTF8-H", BaseFont.NOT_EMBEDDED);
		BaseFont bfChinese = BaseFont.createFont("/fonts//STKAITI.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

		Font FontChinese = new Font(bfChinese, 12, Font.NORMAL);
		FileOutputStream out = new FileOutputStream(pdf);
		Rectangle rect = new Rectangle(PageSize.A4.rotate());
		Document doc = new Document(rect);
		PdfWriter.getInstance(doc, out);
		doc.open();
		Paragraph p = new Paragraph();
		p.setFont(FontChinese);
		BufferedReader read = new BufferedReader(new FileReader(text));
		String line = read.readLine();
		while(line != null){
		System.out.println(line);
			p.add(line+"\n");
			line = read.readLine();
		}
		read.close();
		doc.add(p);
		doc.close();
	}

	public static void main(String[] args) throws Exception {

//	java.io.File file = new java.io.File(TextParser.class.getResource("/").getPath());
	File file = new File("E:/cloud-ba/bookfile");
	String path = file.getPath();
	path = java.net.URLDecoder.decode(path,"UTF-8");
	String text = path+"/1.properties";
//	String text = path+"/a.png";
	String pdf = path+"/4.pdf";

	TextParser p = TextParser.getInstance();
//	p.text2pdf(text, pdf);
//	a(text, pdf);

//	picToPdf(path+"/IMG_4417.JPG", path+"/s.pdf");
	
//	PdfUtil.textToPdf(text, pdf);
	PdfUtil.picToPdf(path+"/2.pdf",path+"/888.JPG");
	}
	
	public static void a(String inputFile,String outputFile) throws Exception {
		// TODO Auto-generated method stub
//		String inputFile = "H://test.html";
		String url = new File(inputFile).toURI().toURL().toString();
//		String outputFile = "H://test.pdf";
		System.out.println(url);
		OutputStream os = new FileOutputStream(outputFile);
		ITextRenderer renderer = new ITextRenderer();
		renderer.setDocument(url);
		// 解决中文支持问题
//		ITextFontResolver fontResolver = renderer.getFontResolver();
//		fontResolver.addFont("C:/Windows/Fonts/simsun.ttc",
//		BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
		// 解决图片的相对路径问题
		renderer.getSharedContext().setBaseURL("file:/d:/");
		renderer.layout();
		renderer.createPDF(os);
		System.out.println(renderer);
//		System.out.println(fontResolver);
		os.close();
		}

}
